package io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.impl;

import io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.DatasourceApi;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.model.LogDTO;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.Jdbc;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.enums.DateSuffixEnum;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.utils.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcRepository implements DatasourceApi {

    private final Logger log = LoggerFactory.getLogger(ElasticsearchRepository.class);

    private final JdbcTemplate operateLogJdbcTemplate;
    private final String baseTableName;
    private final String insertSql;
    private final String pattern;
    private final Boolean haveSuffix;

    public JdbcRepository(JdbcTemplate operateLogJdbcTemplate, Jdbc jdbc) {
        this.operateLogJdbcTemplate = operateLogJdbcTemplate;
        this.baseTableName = jdbc.getTableName();
        this.insertSql = jdbc.getInsertSql();
        this.haveSuffix = jdbc.getSuffix() != null;
        this.pattern = haveSuffix ? DateSuffixEnum.getJdbcSuffixPattern(jdbc.getSuffix()) : "";
    }

    @Override
    public void save(LogDTO logDTO) {
        String tableName = haveSuffix
                ? this.baseTableName + DateTimeUtils.format(logDTO.getCreateTime(), pattern)
                : this.baseTableName;
        try {
            operateLogJdbcTemplate.update(String.format(insertSql, tableName),
                    logDTO.getId(), logDTO.getIp(), logDTO.getOperator(), logDTO.getMethod(), logDTO.getUri(),
                    logDTO.getEndPoint(), logDTO.getClassInfo(), logDTO.getMethodInfo(), logDTO.getSuccess(), logDTO.getRequestBody(),
                    logDTO.getResponseBody(), logDTO.getErrorMessage(), logDTO.getTimeTaken());
        } catch (DataAccessException e) {
            log.warn("OPERATE-LOG JDBC insert log record error.This exception will not affect your main program flow, but operation logging cannot be saved.", e);
        }
    }
}
